<template>
  <div class="container-fluid py-3">

    <!-- 公告卡片 -->
    <div class="row mb-3">
      <div class="col-12">
        <div class="card h-100">
          <div class="card-body">
            <h3 class="card-title mb-3">最新公告</h3>
            <p class="card-text">
              1. 系统升级通知：为了提升系统稳定性，我们将在本月25日进行系统升级，预计升级时间为3小时，期间系统将暂时无法使用，请各位管理员和业主提前做好安排。
            </p>
            <p class="card-text">
              2. 维修申请：目前维修申请的处理时间已缩短至2个工作日，请大家放心提交维修请求，我们会尽快安排专业人员进行处理。
            </p>
            <p class="card-text">
              3. 公共区域安全检查：下周我们将进行小区公共区域的安全检查，包括电梯、消防设施等，请各位业主配合工作人员的检查。
            </p>
            <p class="card-text">
              4. 社区活动：我们将在下个月组织一次大型社区活动，具体活动时间和地点请关注后续通知。
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据统计卡片行 -->
    <div class="row text-center gy-3">
      <!-- 房间空闲数量 -->
      <div class="col-6 col-md-3">
        <div class="card h-100">
          <div class="card-body">
            <h3 class="card-title">房间空闲数量</h3>
            <p class="card-text fs-3 fw-bold">{{ freeRoomCount }}</p>
          </div>
        </div>
      </div>

      <!-- 入住住户 -->
      <div class="col-6 col-md-3">
        <div class="card h-100">
          <div class="card-body">
            <h3 class="card-title">入住住户</h3>
            <p class="card-text fs-3 fw-bold">{{ residentCount }}</p>
          </div>
        </div>
      </div>

      <!-- 入住率 -->
      <div class="col-6 col-md-3">
        <div class="card h-100">
          <div class="card-body">
            <h3 class="card-title">入住率</h3>
            <p class="card-text fs-3 fw-bold">{{ occupancyRate }}%</p>
          </div>
        </div>
      </div>

      <!-- 总房间数量 -->
      <div class="col-6 col-md-3">
        <div class="card h-100">
          <div class="card-body">
            <h3 class="card-title">总房间数量</h3>
            <p class="card-text fs-3 fw-bold">{{ totalRoomCount }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="row text-center mt-4 g-3">
      <div class="col-12 col-md-6">
        <div class="card h-100">
          <div class="card-body">
            <h4 class="card-title mb-3">数据统计图</h4>
            <div id="chart-container" style="height: 300px;"></div>
          </div>
        </div>
      </div>
      <div class="col-12 col-md-6">
        <div class="card h-100">
          <div class="card-body">
            <h4 class="card-title mb-3">房间数据变化趋势</h4>
            <div id="area-chart-container" style="height: 300px;"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 贡献者与使用者信息区 -->
    <div class="row justify-content-center my-4 g-3">
      <!-- 贡献者卡片 -->
      <div class="col-12 col-md-5">
        <div class="card shadow-sm h-100">
          <h2 class="card-title text-center my-3 text-primary">物业后台管理系统贡献者</h2>
          <div class="card-body d-flex align-items-center mb-3">
            <img src="http://www.epmadmarent.com:8088/images/白衣美女.jpg" alt="物业制造者"
              class="rounded-circle border border-primary me-3 img-fluid"
              style="width: 80px; height: 80px; object-fit: cover;">
            <div>
              <h5 class="text-secondary">张伟 - 创始人兼CEO</h5>
              <p class="text-muted mb-0">负责公司战略规划与决策</p>
            </div>
          </div>
          <div class="card-body d-flex align-items-center mb-3">
            <img src="http://www.epmadmarent.com:8088/images/猫娘.jpg" alt="团队成员"
              class="rounded-circle border border-primary me-3 img-fluid"
              style="width: 80px; height: 80px; object-fit: cover;">
            <div>
              <h5 class="text-secondary">李娜 - 技术总监</h5>
              <p class="text-muted mb-0">领导产品技术开发，确保平台稳定运行</p>
            </div>
          </div>
          <div class="card-body d-flex align-items-center mb-3">
            <img src="http://www.epmadmarent.com:8088/images/河边姑娘.jpg" alt="团队成员"
              class="rounded-circle border border-primary me-3 img-fluid"
              style="width: 80px; height: 80px; object-fit: cover;">
            <div>
              <h5 class="text-secondary">王鹏 - 市场总监</h5>
              <p class="text-muted mb-0">负责市场推广与品牌建设</p>
            </div>
          </div>
          <div class="card-body d-flex align-items-center">
            <img src="http://www.epmadmarent.com:8088/images/黑神话.jpg" alt="团队成员"
              class="rounded-circle border border-primary me-3 img-fluid"
              style="width: 80px; height: 80px; object-fit: cover;">
            <div>
              <h5 class="text-secondary">赵敏 - 客户服务总监</h5>
              <p class="text-muted mb-0">负责客户服务与用户支持</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 使用者卡片 -->
      <div class="col-12 col-md-5">
        <div class="card shadow-sm h-100">
          <h2 class="card-title text-center my-3 text-success">物业管理系统功能</h2>
          <div class="card-body">
            <p class="card-text text-muted">
              本系统为物业管理提供了一站式解决方案，涵盖房屋管理、数据统计等功能，帮助物业管理员和业主高效管理和查询物业信息。
            </p>
            <ul class="list-group list-group-flush">
              <li class="list-group-item">
                <strong class="text-success">房屋管理：</strong>
                管理物业中的房间信息，包括空闲房、已入住房、房屋状态等。
              </li>
              <li class="list-group-item">
                <strong class="text-success">数据统计：</strong>
                提供实时数据统计与分析，包括入住率、房间空闲数量等，帮助管理员进行决策。
              </li>
            </ul>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  setup() {
    const token = ref(localStorage.getItem('token'));
    const freeRoomCount = ref(0);
    const residentCount = ref(0);
    const occupancyRate = ref(0);
    const totalRoomCount = ref(0);

    const fetchFreeRoomCount = async () => {
      if (token.value) {
        try {
          const response = await axios.get('http://localhost:3008/unitsList', {
            headers: {
              Authorization: `Bearer ${token.value}`,
            },
          });

          // 过滤状态为 "空闲" 的房间数量
          const freeRooms = response.data.data.filter(unit => unit.status === '空闲');
          freeRoomCount.value = freeRooms.length;

        } catch (error) {
          console.error('获取房间空闲数量失败:', error);
        }
      }
    };


    const fetchResidentCount = async () => {
      if (token.value) {
        try {
          const response = await axios.get('http://localhost:3008/ownerList', {
            headers: {
              'Authorization': `Bearer ${token.value}`
            }
          });
          residentCount.value = response.data.data.length;
        } catch (error) {
          console.error('获取入住住户数量失败:', error);
        }
      }
    };

    const fetchOccupancyRate = async () => {
      if (token.value) {
        try {
          const response = await axios.get('http://localhost:3008/unitsList', {
            headers: {
              'Authorization': `Bearer ${token.value}`
            }
          });
          const totalRooms = response.data.data.length;
          const occupiedRooms = response.data.data.filter(unit => unit.status === '已入住').length;
          totalRoomCount.value = totalRooms;
          occupancyRate.value = ((occupiedRooms / totalRooms) * 100).toFixed(2); // 计算入住率
        } catch (error) {
          console.error('获取入住率失败:', error);
        }
      }
    };

    const myChart = ref(null);
    const areaChart = ref(null);

    const updateChart = () => {
      if (myChart.value) {
        myChart.value.setOption({
          title: {
            text: '物业管理数据统计',
            left: 'center',
            top: '20'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          series: [
            {
              name: '数据统计',
              type: 'pie',
              radius: '50%',
              data: [
                { value: freeRoomCount.value, name: '空闲房间' },
                { value: residentCount.value, name: '入住住户' },
                { value: occupancyRate.value, name: '入住率 (%)' },
                { value: totalRoomCount.value, name: '总房间数量' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowOffsetY: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    };

    const updateAreaChart = () => {
      if (areaChart.value) {
        areaChart.value.setOption({
          title: {
            text: '房间数据变化趋势',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: ['空闲房', '入住住户', '入住率(%)', '总房间数']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: [
                freeRoomCount.value,
                residentCount.value,
                parseFloat(occupancyRate.value),
                totalRoomCount.value
              ],
              type: 'line',
              areaStyle: {}
            }
          ]
        });
      }
    };

    onMounted(() => {
      // 初始化图表
      myChart.value = echarts.init(document.getElementById('chart-container'));
      areaChart.value = echarts.init(document.getElementById('area-chart-container')); // 初始化区域图表

      // 执行所有数据请求
      Promise.all([
        fetchFreeRoomCount(),
        fetchResidentCount(),
        fetchOccupancyRate()
      ]).then(() => {
        updateChart();
        updateAreaChart();
      });
    });

    return {
      freeRoomCount,
      residentCount,
      occupancyRate,
      totalRoomCount
    };
  }
};
</script>

<style scoped>
.card-title {
  font-size: 1.2rem;
  font-weight: 600;
}

@media (max-width: 767px) {
  .card-title {
    font-size: 1rem;
  }
}
</style>
